<template>
  <view class="phxx-item-detail">
    <!-- 采购接单 -->
    <view class="content-box" v-show="!showReadMe">
      <view class="title-item">
        基本信息
      </view>
      <view class="bottom block-back">
        <view class="uni-form-item" v-if="!!waybillData.waybillRespVO.purchaser">
          <view class="title">货主</view>
          <input class="uni-input disab-box" disabled v-model="waybillData.waybillRespVO.purchaser" />
        </view>
        <view class="uni-form-item">
          <view class="title">装货地</view>
          <input class="uni-input disab-box" disabled v-model="waybillData.waybillRespVO.loadingSiteName" />
        </view>
        <view class="uni-form-item">
          <view class="title">卸货地</view>
          <input class="uni-input disab-box" disabled v-model="waybillData.waybillRespVO.landingPlace" />
        </view>
        <view class="uni-form-item">
          <view class="title">运价(元/吨)</view>
          <input class="uni-input disab-box" disabled v-model="waybillData.waybillRespVO.freight" />
        </view>
      </view>
      <view class="title-item">
        司机信息
      </view>
      <view class="bottom block-back">
        <view class="uni-form-item">
          <view class="title">司机姓名</view>
          <input class="uni-input disab-box" disabled v-model="waybillData.waybillRespVO.carName" />
        </view>
        <view class="uni-form-item">
          <view class="title">身份证号</view>
          <input class="uni-input disab-box" disabled v-model="driverCard" />
          <!--          网货onlineGoodsSwitch == 1显示-->
          <view v-if="isNetFlag" :class="{
            'red-type': waybillData.waybillRespVO.uploadStatus == 0 || waybillData.waybillRespVO.uploadStatus == 2,
            'green-type': waybillData.waybillRespVO.uploadStatus == 1,
            'status': true}" style="border: none;font-size: 14px;display: flex; align-items: center;">
            <uni-icons v-if="waybillData.waybillRespVO.uploadStatus == 0 || waybillData.waybillRespVO.uploadStatus == 2"
              type="info-filled" size="20" color="#FF0000" />
            <uni-icons v-else-if="waybillData.waybillRespVO.uploadStatus == 1" type="checkbox-filled" size="20"
              color="#66cc33" />
            {{ statusName[waybillData.waybillRespVO.uploadStatus] || '' }}
          </view>
        </view>
        <!--          上传状态为失败或者未上传 && 网货onlineGoodsSwitch == 1显示-->
        <span
          v-if="(waybillData.waybillRespVO.uploadStatus == 0 || waybillData.waybillRespVO.uploadStatus == 2) && isNetFlag"
          style="font-size: 15px; color: #ff8800;">
          注意: 如果未上传或上传失败会影响运费结算,请点击
          <span style="font-size: 16px; color: #0088ff; text-decoration: underline; cursor: pointer;"
            @click="handleClick">重新上传</span>
        </span>
      </view>
      <view class="title-item">
        拉运信息
      </view>
      <view class="bottom block-back">
        <view class="uni-form-item">
          <view class="title"><span style="color:red;">*</span>产品</view>
          <input class="uni-input disab-box" disabled v-model="waybillData.waybillRespVO.proName" />
        </view>
        <view class="uni-form-item">
          <view class="title"><span style="color:red;">*</span>车牌号</view>
          <input class="uni-input disab-box" disabled :value="selectedCar" placeholder="请选择车辆" @click="open" />
          <!--          网货onlineGoodsSwitch == 1显示-->
          <view v-if="isNetFlag" :class="{
            'red-type': waybillData.waybillRespVO.uploadStatusCar == 0 || waybillData.waybillRespVO.uploadStatusCar == 2,
            'green-type': waybillData.waybillRespVO.uploadStatusCar == 1,
            'status': true}" style="border: none;font-size: 14px;display: flex; align-items: center;">
            <uni-icons
              v-if="waybillData.waybillRespVO.uploadStatusCar == 0 || waybillData.waybillRespVO.uploadStatusCar == 2"
              type="info-filled" size="20" color="#FF0000" />
            <uni-icons v-else-if="waybillData.waybillRespVO.uploadStatusCar == 1" type="checkbox-filled" size="20"
              color="#66cc33" />
            {{ statusName[waybillData.waybillRespVO.uploadStatusCar] == undefined ? '':
            statusName[waybillData.waybillRespVO.uploadStatusCar]}}
          </view>
        </view>
        <!--          上传状态为失败 && 网货onlineGoodsSwitch == 1显示-->
        <span
          v-if="(waybillData.waybillRespVO.uploadStatusCar == 0 || waybillData.waybillRespVO.uploadStatusCar == 2) && isNetFlag"
          style="font-size: 15px; color: #ff8800;">注意: 如果未上传或上传失败会影响运费结算,请点击
          <span style="font-size: 16px; color: #0088ff; text-decoration: underline; cursor: pointer;"
            @click="handleCarClick">重新上传</span>
        </span>
        <view class="uni-form-item">
          <view class="title"><span style="color:red;">*</span>矿发皮重</view>
          <input class="uni-input" type="digit" :class="{'disab-box':isDisabled}" v-model="tareWeight"
            placeholder="请输入矿发皮重" @blur="inputTareWeight" :disabled="isDisabled" />
          吨
        </view>
        <view class="uni-form-item">
          <view class="title"><span style="color:red;">*</span>矿发毛重</view>
          <input class="uni-input" type="digit" :class="{'disab-box':isDisabled}" v-model="grossWeight"
            placeholder="请输入矿发毛重" @blur="inputGrossWeight" :disabled="isDisabled" />
          吨
        </view>
        <view class="uni-form-item">
          <view class="title"><span style="color:red;">*</span>矿发净重</view>
          <input class="uni-input" type="digit" :class="{'disab-box':isDisabled}" v-model="netWeight" placeholder="0"
            @blur="inputWeight" :disabled=true />
          吨
        </view>

        <view class="uni-form-item">
          <view class="demonstration title"><span style="color:red;">*</span>矿发时间</view>
          <w-picker :visible="poundListFlag" mode="date" startYear="1900" endYear="2124" class="disab-box"
            :value="curDateTime" :current="false" fields="second" @confirm="onConfirm($event,'date1')"
            @cancel="onCancel" :disabled-after="false" ref="date1"></w-picker>
          <input class="uni-input prd-mess" disabled :class="{'disab-box':isDisabled}" v-model="datetimesingle"
            placeholder="请选择矿发时间" @click="poundListFlag=true"></input>
        </view>

        <!--				<view class="uni-form-item" style="height: 220rpx;justify-content: flex-start;">-->
        <!--					<view class="title"><span style="color:red;">*</span>矿发磅单</view>-->
        <!--          <view class="imageStyle" v-if="imagesPath.length > 0">-->
        <!--            <uni-icons type="close" size="20" class="close-icon" color="#fff" @click="deleteImg(imagesPath[0])"></uni-icons>-->
        <!--            <image class="cover-img band-img first-img"  :src="imagesPath[0]" @click="clickImg" mode="aspectFill">-->
        <!--            </image>-->
        <!--          </view>-->
        <!--					<image class="cover-defaultImg band-img" @click="select1" :src="imagesDefaultPath" mode="aspectFill"></image>-->
        <!--				</view>-->

        <view class="uni-form-item" style="height: 320rpx;justify-content: flex-start;">
          <view class="title"><span style="color:red;">*</span>矿发磅单</view>
          <uni-file-picker :limit="1" title=" " v-model="OreDevelopment" file-mediatype="image" mode="grid"
            @select="select($event, 'oreDevelopment')" :disable-preview="false"
            @delete="deletephoto($event,'oreDevelopment')"></uni-file-picker>
        </view>
        <view class="uni-form-item" style="height: 320rpx;justify-content: flex-start;" v-if="isSealpicturesFlag">
          <view class="title"><span style="color:red;">*</span>铅封照片</view>
          <uni-file-picker :limit="3" title=" " v-model="sealpictures" file-mediatype="image" mode="grid"
            @select="select($event, 'sealPictures')" :disable-preview="false"
            @delete="deletephoto($event,'sealPictures')"></uni-file-picker>
        </view>
        <!--				<view class="uni-form-item">-->
        <!--					<view class="title"><span v-if="isNetFlag" style="color:red;">*</span>收款银行卡</view>-->
        <!--					<input class="uni-input disab-box" disabled :value="accountValue" @click="openCard"/>-->
        <!--				</view>-->

      </view>
      <!--          网货onlineGoodsSwitch == 1显示-->
      <view v-if="isNetFlag">
        <view class="title-item" style="display: flex; justify-content: space-between; align-items: center;">
          收款信息
          <span v-if="" style="font-size: 15px; color: #ff8800;margin-left: auto;">点击
            <span style="font-size: 16px; color: #0088ff; text-decoration: underline; cursor: pointer;"
              @click="updataDataClick">更新</span>
            获取最新收款信息
          </span>
        </view>
        <view class="bottom block-back">
          <view class="uni-form-item">
            <view class="title"><span v-if="isFlag" style="color:red;">*</span>收款方式</view>
            <input class="uni-input disab-box" disabled :value="receiptValue" @click="openReceipt" />
          </view>
          <view class="uni-form-item">
            <view class="title" v-if="backImgAddShow"><span v-if="isFlag" style="color:red;">*</span>收款银行卡</view>
            <view class="title" v-else><span v-if="isFlag" style="color:red;">*</span>收款账户</view>
            <input class="uni-input disab-box" disabled :value="accountValue" @click="openAccount" />
          </view>
          <span v-if="backImgAddShow" style="font-size: 15px; color: #ff8800;margin-left: auto;">说明:
            本人收款可添加银行卡,非本人无需添加。如存在收款账户问题请联系卡漠客服!</span>
        </view>
      </view>
      <view class="btns">
        <button :class="{ 'loading': isLoading }" type="primary" @click="handleJieDan">
          接单{{ (!!payAmount && payAmount > 0) ? "（"+ payAmount +"）元" : "" }}
          <view v-if="isLoading" class="loading-icon"></view>
        </button>
      </view>

    </view>
    <!-- 运输计划作废提示弹窗 -->
    <!-- <uni-popup ref="tipsShow" mode="center" width="300rpx" border-radius="20" :mask-close-able="false">
      <view class="tipsBox">
        <view class="tipsHeader">
          提示
        </view>
        <view class="tipsDesc">
          {{tipsMess}}
        </view>
        <view class="tipsBtn">
          <navigator target="miniProgram" class="btn" open-type="exit" @click="closeTipsWin">确认</navigator>
        </view>
      </view>
    </uni-popup> -->
    <!-- 车辆选择弹窗 -->
    <uni-popup class="carPop" ref="popup">
      <view class="carList">
        <view class="top">
          <view class="title">
            选择车牌
            <view class="cph" @click="handleAddCar">
              <image :src="backImgAdd"></image>
            </view>
          </view>
        </view>
        <view class="a-i-c">
          <view v-for="(item, index) in vehicleList" :key="index">
            <view class="item-box" :class="{'car-box': index == (vehicleList.length -1)} " @click="handleCar(item)">
              <view class="cph">
                <image :src="carImg"></image>{{ item.vehicleNo }}
              </view>
              <view class="status">
                <text class="isReal" v-if="item.isIdentified">已认证</text>
                <text class="isnotReal" @click="recognizeCar(item)" v-else>未认证</text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </uni-popup>
    <!-- 银行卡选择弹窗 -->
    <!--		<uni-popup class="cardPop" ref="popupCard" >-->
    <!--			<view class="carList">-->
    <!--				<view class="top">-->
    <!--					<view class="title">-->
    <!--						选择银行卡-->
    <!--						<view class="cph"  @click="addCardFun"><image :src="backImgAdd"></image></view>-->
    <!--					</view>-->
    <!--				</view>-->
    <!--				<view class="a-i-c">-->
    <!--					<view v-for="(item, index) in accountRange" >-->
    <!--						<view class="item-box" :class="{'car-box': index == (accountRange.length -1)} "  @click="changeAccount(item)">-->
    <!--							<view class="cph"><image :src="backImg"></image>{{ item.text }}</view>-->
    <!--						</view>-->
    <!--					</view>-->
    <!--				</view>-->
    <!--			</view>-->
    <!--		</uni-popup>-->
    <!-- 收款账户选择弹窗 -->
    <uni-popup class="cardPop" ref="popupAccount">
      <view class="carList">
        <view class="top">
          <view class="title">
            选择{{accountMsg}}账户
            <view class="cph" @click="addCardFun" v-if="backImgAddShow">
              <image :src="backImgAdd"></image>
            </view>
          </view>
        </view>
        <view class="a-i-c">
          <view v-for="(item, index) in balanceOrBankRange" :key="index">
            <view class="item-box" :class="{'car-box': index == (balanceOrBankRange.length -1)} "
              @click="changeBalanceOrBankRange(item)">
              <view class="cph">
                <image :src="backImgAddShow ? backImg : balanceImg"></image>{{ item.value }}
              </view>
            </view>
          </view>
        </view>
      </view>
    </uni-popup>
    <!-- 收款方式选择弹窗 -->
    <uni-popup class="cardPop" ref="popupReceipt">
      <view class="carList">
        <view class="top">
          <view class="title">
            选择收款方式
          </view>
        </view>
        <view class="a-i-c">
          <view v-for="(item, index) in receiptRange" :key="index">
            <view class="item-box" :class="{'car-box': index == (receiptRange.length -1)} "
              @click="changeReceipt(item)">
              <view class="cph">
                <image :src="item.text === '银行卡' ? backImg : balanceImg"></image>{{ item.text }}
              </view>
            </view>
          </view>
        </view>
      </view>
    </uni-popup>
    <!-- 接单确认弹窗 -->
    <uni-popup class="linePaymentPop" ref="payConfirmDialog">
      <view class="payconfirmBox">
        <view class="main-box">
          <view class="top">
            <view @click="exit" class="close">X</view>
            <view class="title"></view>
            <view class="btn" @click="toChargeFun">充值</view>
          </view>
          <view class="content">
            <view class="money">
              ￥{{ payAmount }}元
            </view>
            <view class="showing">
              <view>付款方式</view>
              <view>钱包支付</view>
            </view>
          </view>
        </view>
        <view class="btn-box">
          <button :class="{ 'loading': isLoading }" class="agreeBtn" size="default" type="primary"
            @click="handleOrderPay">
            确认接单
            <view v-if="isLoading" class="loading-icon"></view>
          </button>
        </view>
      </view>
    </uni-popup>
    <!-- 阅读 -->
    <view v-if="showReadMe">
      <view class="back-meng"></view>
      <view class="phxx-itemss">
        <view class="header">
          <view class="title">《华业开泰运输管理协议》</view>
        </view>
        <view class="top">
          <view>司机考核要求，进入站台重车司机发生发现以下情形，视情况确认执行以下制度：</view>
          <view class="tit">
            1、进入集运站的大型运输车辆，车速不得超过 5 公里/小时。超速者扣除运费 50 元造成事故移交公安机关处理。
          </view>
          <view class="tit">
            2、进入集运站的大型运输车辆，按照华业开泰相关规定扫 码登记，未按照规定扫码，登记强行闯杆者给予扣除运费 100~300 元。
          </view>
          <view class="tit">
            3、大型运输车辆做好环保遮盖工作，在磅房前 20
            米指定区域揭开遮盖篷布后方可上磅，并积极配合工作人员查验煤质，不揭篷布、不配合查验煤质者，给予扣除运费100~500元;运输车辆环保工作不到位，致使运输货物抛洒路面，视其情节轻重给予扣除运费 100~200 元。
          </view>
          <view class="tit">
            4、严禁洒水，一经发现罚款3000元。
          </view>
        </view>
        <view class="btn">
          <view class="read">
            <view class="read-box" @click="handleChange">
              <image v-if="agree" :src="checkImg" style="width: 30rpx; height: 30rpx"></image>
              <image v-else :src="uncheckImg" style="width: 30rpx; height: 30rpx"></image>
            </view>
            我已阅读并同意
          </view>
          <button :class="{ 'not-read': !agree }" type="primary" @click="closeLinepop">
            同意
          </button>
        </view>
      </view>
    </view>
    <uni-popup class="jdcgPop" ref="jdcgPop" :mask-click="false">
      <view class="top">
        <view class="title-box">
          <view class="tit1">
            <image :src="imagesSuccess" class="logo" mode="widthFix"></image>
          </view>
          <view class="title">
            车辆<font style="color: #409efe">【{{ selectedCar }}】</font>接单成功！
          </view>
          <view v-if="isOtherTip" class="tit1"> 车辆进入蓝色区域请尽快在小程序签到排号，<font style="color: red">未排号或未叫号车辆将无法入场</font>
          </view>
        </view>
        <view class="body">
          <view class="tit"> 温馨提示： </view>
          <view class="tit">
            <view class="icon">
              <view class="icon-inner"></view>
            </view>
            <view>请务必携带<font style="color: #FF4D4F">有效身份证</font>，否则会无法入场过磅。</view>
          </view>
          <view v-if="isOtherTip" class="tit">
            <view class="icon">
              <view class="icon-inner"></view>
            </view>
            <font style="color: #409EFE">蓝色区域</font>为排队区域。
          </view>
          <view v-if="isOtherTip" class="tit">
            <view class="icon">
              <view class="icon-inner"></view>
            </view>
            <font style="color: #FF4D4F">红色区域</font>为禁停区域（未叫号禁止入内）。
          </view>
          <view v-if="isOtherTip" class="tit">
            <view class="icon">
              <view class="icon-inner"></view>
            </view>
            <font>收到叫号进场通知，请在规定时间入场，否则将自动作废。关注公众号【神煤交易智慧计量】及时获取信息！</font>
          </view>
        </view>
        <view class="btn" style="margin-top:120rpx">
          <button type="primary" plain size="default" :disabled="isCounting" :class="{ 'disabled-button': isCounting }"
            @click="confirmJieDan">
            {{ isCounting ? `确认 (${countdown}s)` : '确认' }}
          </button>
        </view>
      </view>
    </uni-popup>
    <tip-box :show="showBlacklistTip" :message="blacklistTip" :duration="8000" @showTip="showTip"></tip-box>
  </view>
</template>
<script>
  import func from '@/utils/funlogin.js';
  import { getLists } from '@/api/system/bank.js';
  import { setTenantId, getOpenId, getTenantId, getAccessToken, setWayBillNo, getWayBillNo, setToken, setDriverId, getDriverId } from '@/utils/auth';
  import { getOpenIdByCode, getTenantsByOpenId, getPhoneByOpenid, wxPhoneLogin } from '@/api/login.js';
  import { getTenantPayConfig } from '@/api/system/user.js';
  import { getWaybNbyTenantid, getWaybCost, payWaybillCost, getDriverMoney } from '@/api/system/waybill.js';
  import {
    getCustList, getLineUpByDriver, checkRuningCar, getWayBillDetail, getLineUpDetail,
    getWayBillDetailLatest, getProductsLists, getTransPlanDetail,
    getVehicle, addWaybillJiyun, getTenantConfig, addWaybillLists, findLineupSwitchByTenant, findDriverWaybill,
    getDrivingList, getPayeeInfoLists, getDictDatas
  } from '@/api/me.js';
  import { toast, getCurrenDate, showConfirm, dictTansParams } from '@/utils/common';
  import config from '@/config'
  import { getDeliverOne } from '../api/system/goods';

  export default {
    data() {
      return {
        payOriginalVal: undefined,
        statusName: {
          "0": '未上传',
          "1": '上传成功',
          "2": '上传失败',
        },
        failed: undefined,
        failedCar: undefined,
        accountMsg: '',
        backImgAddShow: false,
        lineupSwitch: 1,
        errorMsg: undefined,
        agree: false,
        showReadMe: false,
        payAmount: 0,
        isLoading: false,
        payCostFlag: false,
        selectedCard: '',
        isNetFlag: false,
        isFlag: true,
        isSealpicturesFlag: false,
        waybDialog: false,
        tipsMess: '',
        accountValue: undefined,
        receiptValue: undefined,
        accountIdValue: undefined,
        receiptIdValue: undefined,
        ServiceCode: undefined,
        accountRange: [],
        receiptRange: [],
        bankCardAccountRange: [],
        balanceAccountRange: [],
        balanceOrBankRange: [],
        coalmineFlag: false,
        curDateTime: '',
        curDateTime2: '',
        poundListFlag: false,
        switchText: "我的排号",
        isNeedLineup: true,
        planId: undefined,
        driverCard: '',
        datetimesingle: undefined,
        datetimesingle2: undefined,
        grossWeight: undefined,
        tareWeight: undefined,
        netWeight: undefined,
        currentPayStatus: false,
        waybillDialogFlag: false,
        waybillDialogDetailFlag: false,
        waybillFinishDialogFlag: false,
        refreshFlag: false,
        showCard: false,
        contractImg: config.baseImgUrl + '/contract-up.svg',
        contractupImg: config.baseImgUrl + '/contract.svg',
        currentStatus: false,
        loading: false,
        imagesDefaultPath: config.baseImgUrl + '/img.png',
        sealpictures: [],
        OreDevelopment: [],
        waybillStatusName: 0,
        isPdDistance: false,
        imagesPath: [],
        imagesPath2: [],
        isJieDan: false,
        isJiedanRead: false,
        imagesDefaultPath2: config.baseImgUrl + '/img.png',
        carListFlag: false,
        jTNum: 0,
        waybillStatusPay: false,
        hasLoadPage: false, // 上传照片 onshow
        vehicleList: [],
        selectedCar: '',
        selectedProd: undefined,
        ysjhData: '', // 从接单而来的参数
        currentWIndow: '',
        showBlacklistTip: false,
        blacklistTip: '',
        waybillData: {
          waybillRespVO: {
            uploadStatus: undefined,
            uploadStatusCar: undefined,
            transportPlanId: undefined,
            purchaseId: undefined,
            purchaser: undefined,
            proName: undefined,
            proId: undefined,
            landingPlaceId: undefined,
            landingPlace: undefined,
            cargoOwnerld: undefined,
            cargoOwnerName: undefined,
            netCargoCompanyId: undefined,
            netCargoCompanyName: undefined,
            landingPoint: undefined,
            landingPointName: undefined,
            agentId: undefined,
            agentName: undefined,
            informationFee: undefined,
            settlementBasis: undefined,
            erasureRule: undefined,
            loadingSiteId: undefined,
            loadingSiteName: undefined,
            supName: undefined,
            freight: undefined,
            planType: undefined,
            cusTransport: undefined,
            carName: undefined,
            carCard: undefined,
            driverId: undefined,
            carPhone: undefined,
            uuid: undefined,
            orderCost: undefined,
            supId: undefined,
            mineralGrossWeight: undefined,
            mineralTareWeight: undefined,
            mineralNetWeight: undefined,
            mineralTime: undefined,
            userId: undefined,
            enterId: undefined,
            openId: undefined,
            planNo: undefined,
            planTypeName: undefined,
            waybillNo: undefined,
            sealPhotographs: [],
            freightCollectionAccountId: undefined,
            freightCollectionType: undefined,
            netGoodsServiceCode: undefined,
            freightCollectionAccount: undefined,
          },
          hours: 0,
          minutes: 0,
          currentLineupCount: 0,
          enableStatus: undefined
        },
        priceNum: 0,
        priceNumText: '排号',
        payRefundTime: 0,
        sjjdFormData: {},
        queryParam: {
          pageNo: 1,
          pageSize: 100
        },
        waybillNo: '',
        imageStyles: {
          width: 100,
          height: 100
        },
        cuttentType: '',
        payParam: {
          timeStamp: '',
          paySign: '',
          nonceStr: '',
          package: ''
        },
        custList: [],
        supId: undefined,
        curType: 2,
        rowNumberData: [],
        rowKey: ['customerName', 'waybillStatusName'],
        wayBillStatusList: [],
        queryParam: {
          pageNo: 1,
          pageSize: 3,
          vehicleNo: '',
          startTime: '',
          endTime: ''
        },
        pageParams: {
          isMore: 'more'
        },
        payeeInfoParam: {
          goodsId: undefined,
          vehicleNo: undefined,
          networkFreight: undefined,
        },
        msgStatus: false,
        flag: false,
        carBrandId: undefined,
        isCounting: false,
        countdown: 5,
        isOtherTip: false
      };
    },
    methods: {
      //司机重新上传
      handleClick() {
        uni.showModal({
          title: '提示信息',
          content: "失败原因为: " + this.failed,
          cancelText: '取消',
          confirmText: '立即处理',
          success: (res) => {
            if (res.confirm) {
              //跳转司机认证
              this.setStorageDatas()
              uni.setStorageSync('isSetSjxx', 'net');
              uni.navigateTo({
                url: '/packageB/pages/mine/driver-auth/driver-auth?type=code'
              });
            }
          }
        })
      },
      //获取最新收款信息
      updataDataClick() {
        if (this.selectedCar == '' || this.selectedCar == undefined) {
          toast('请先选择车辆')
          return
        } else {
          this.getReceiptTypeList(this.selectedCar)
          if (this.msgStatus) {
            toast('更新成功')
          }
        }
      },
      //车辆重新上传
      handleCarClick() {
        uni.showModal({
          title: '提示信息',
          content: "失败原因为: " + this.failedCar,
          cancelText: '取消',
          confirmText: '立即处理',
          success: (res) => {
            if (res.confirm) {
              //跳转司机认证
              this.setStorageDatas()
              uni.setStorageSync('isSetSjxx', 'net');
              uni.navigateTo({
                url: `/packageB/pages/common/vehicle-editing/vehicle-authentica?id=${this.carBrandId}`
              });
            }
          }
        })
      },
      handleChange() {
        this.agree = !this.agree
      },
      closeLinepop() {
        if (!this.agree) return
        this.showReadMe = false
      },
      changeAccount(res) {
        // uni.setStorageSync('cardbankByCode',res);
        this.waybillData.waybillRespVO.freightCollectionAccount = res.text
        this.accountValue = res.text
        this.$refs['popupCard'].close();
      },
      //选择收款账户
      changeBalanceOrBankRange(res) {
        this.accountIdValue = res.id
        this.accountValue = res.value
        this.$refs['popupAccount'].close();
      },
      //选择收款方式
      changeReceipt(res) {
        this.receiptIdValue = res.value
        this.receiptValue = res.text
        this.balanceOrBankRange = []
        this.accountValue = ''
        this.accountMsg = ''
        this.backImgAddShow = false
        if (res.value === 1) {
          this.balanceOrBankRange = this.bankCardAccountRange
          this.accountMsg = '银行卡'
          this.backImgAddShow = true
        } else {
          this.balanceOrBankRange = this.balanceAccountRange
          this.accountMsg = '余额'
        }
        this.$refs['popupReceipt'].close();
      },
      exit() {
        this.$refs['payConfirmDialog'].close();
      },
      // 输入框校验
      inputWeight(e) {
        let value = e.detail.value.trim();
        if (!value) return toast('矿发净重范围为0.01-200,请核实')
        const numRegex = /^(\d+(\.\d*)?|\.\d+)$/;
        if (!numRegex.test(value)) {
          toast('矿发净重范围为0.01-200,请核实')
          this.netWeight = undefined;
        } else {
          if (value < 0.01 || value > 100) {
            toast('矿发净重范围为0.01-200,请核实');
            this.netWeight = undefined;
          }
        }
      },
      inputTareWeight(e) {
        let value = e.detail.value.trim();
        if (!value) return toast('请输入0.01-200的矿发皮重')
        const numRegex = /^(\d+(\.\d*)?|\.\d+)$/;
        if (!numRegex.test(value)) {
          toast('请输入0.01-200的矿发皮重')
          this.tareWeight = undefined;
        } else {
          if (value < 0.01 || value > 200) {
            toast('请输入0.01-200的矿发皮重');
            this.tareWeight = undefined;
          } else if (!!this.grossWeight) {
            this.netWeight = (Number(this.grossWeight) - Number(this.tareWeight)).toFixed(2)
            if (this.netWeight < 0.01 || this.netWeight > 200) {
              toast('矿发净重范围为0.01-200,请核实')
            }
          }
        }
      },
      inputGrossWeight(e) {
        let value = e.detail.value.trim();
        if (!value) return toast('请输入0.01-200的矿发毛重')
        const numRegex = /^(\d+(\.\d*)?|\.\d+)$/;
        if (!numRegex.test(value)) {
          toast('请输入0.01-200的矿发毛重')
          this.grossWeight = undefined;
        } else {
          if (value < 0.01 || value > 200) {
            toast('请输入0.01-200的矿发毛重');
            this.grossWeight = undefined;
          } else if (!!this.tareWeight) {
            this.netWeight = (Number(this.grossWeight) - Number(this.tareWeight)).toFixed(2)
            if (this.netWeight < 0.01 || this.netWeight > 200) {
              toast('矿发净重范围为0.01-200,请核实')
            }
          }
        }
      },
      addCardFun() {
        this.setStorageDatas()
        uni.setStorageSync('isSetSjxx', 'net')
        uni.navigateTo({
          url: '/packageB/pages/mine/bank-card/band-card-add?types=code'
        });
      },
      toChargeFun() {
        this.setStorageDatas()
        uni.setStorageSync('purchasePayNum', this.payAmount);
        uni.setStorageSync('isSetSjxx', 'net')
        this.$tab.navigateTo('/packageB/pages/mine/my-wallet/recharge?types=code');
      },
      setStorageDatas() {
        let _ = this
        uni.setStorageSync('netweightByCode', _.netWeight);
        uni.setStorageSync('tareWeightByCode', _.tareWeight);
        uni.setStorageSync('grossWeightByCode', _.grossWeight);
        uni.setStorageSync('datetimeJiedanByCode', _.datetimesingle);
        uni.setStorageSync('vehicleNoByCode', _.waybillData.waybillRespVO.carBrand);
        uni.setStorageSync('loadingWeighbridgeByCode', _.OreDevelopment);
        uni.setStorageSync('cardbankByCode', _.waybillData.waybillRespVO.freightCollectionAccount);
        if (this.isSealpicturesFlag) {
          uni.setStorageSync('sealpicturesByCode', _.sealpictures);
        }
      },
      removeStorageDatas() {
        uni.removeStorageSync('vehicleNoByCode');
        uni.removeStorageSync('loadingWeighbridgeByCode');
        uni.removeStorageSync('netweightByCode');
        uni.removeStorageSync('tareWeightByCode');
        uni.removeStorageSync('grossWeightByCode');
        uni.removeStorageSync('datetimeJiedanByCode');
        uni.removeStorageSync('cardbankByCode');
        uni.removeStorageSync('isSetSjxx');
        uni.removeStorageSync('purchasePayNum');
        uni.removeStorageSync('sealpicturesByCode');
      },
      //获取银行卡列表
      // async getBankCardList() {
      // 	try {
      // 		let res = await getLists();
      // 		if (res.code == 0) {
      // 			this.accountRange = []
      // 			if(res.data.length > 0){
      // 				res.data.forEach(item=>{
      // 					this.accountRange.push({
      // 						value: item.cardNumber,
      // 						text: item.cardNumber
      // 					})
      // 				})
      // 			}
      // 		}
      // 	} catch (e) {
      // 		return false;
      // 	}
      // },

      //获取收款方式和收款账户列表
      async getReceiptTypeList(vehicleNo) {
        this.payeeInfoParam.vehicleNo = vehicleNo
        this.receiptRange = []
        // this.getDictLists()
        this.receiptRange.push({
          value: 1,
          text: '银行卡'
        }, {
          value: 2,
          text: '余额'
        }
        )
        this.bankCardAccountRange = []
        this.balanceAccountRange = []
        try {
          let res = await getPayeeInfoLists(this.payeeInfoParam);
          this.ServiceCode = res.code
          if (res.code == 0) {
            if (res.data.length > 0) {
              res.data.forEach(item => {
                if (item.code === "1") { // 如果是银行卡类型
                  item.items.forEach(bankItem => {
                    this.bankCardAccountRange.push({
                      id: bankItem.id,
                      userId: bankItem.userId,
                      value: bankItem.value,
                    });
                  });
                } else if (item.code === "2") { // 如果是余额类型
                  item.items.forEach(balanceItem => {
                    this.balanceAccountRange.push({
                      id: balanceItem.id,
                      userId: balanceItem.userId,
                      value: balanceItem.value,
                    });
                  });
                }
              });
              this.msgStatus = true
            }
          } else if (res.code == 100419999) {
            this.isFlag = false
            this.msgStatus = true
          } else {
            toast(`${res.msg}`);
            this.msgStatus = false
          }
        } catch (e) {
          this.msgStatus = false
          return false;
        }
      },
      // 接单为网货时，获取司机信息以及上传网货状态
      async getDriverDataList(netCargoCompanyId) {
        try {
          let res = await getDrivingList(netCargoCompanyId);
          if (res.code == 0) {
            if (res.data != null) {
              this.failed = res.data.remark == null ? '' : res.data.remark
              this.waybillData.waybillRespVO.uploadStatus = res.data.auditStatus == null ? 0 : res.data.auditStatus
              this.waybillData.waybillRespVO.carName = res.data.driverName
              this.waybillData.waybillRespVO.carCard = res.data.idNo
              this.driverCard = res.data.idNo.slice(0, 3) + '****' + res.data.idNo.slice(-3)
              this.waybillData.waybillRespVO.driverId = res.data.id
              this.waybillData.waybillRespVO.carPhone = res.data.mobile
            }
          }
        } catch (e) {
          return false;
        }
      },
      onConfirm(res, type) {
        this.datetimesingle = res.result
        this.poundListFlag = false
      },
      onCancel() {
        this.poundListFlag = false
      },

      getLinePay(price, time) {
        this.priceNum = parseFloat(price / 100).toFixed(2)
        this.priceNumText = `排号(${this.priceNum}元)`
        this.payRefundTime = time
      },
      cancelFirm() {
        this.$refs['payConfirmShow'].close();
      },
      clickImg() {
        let _this = this;
        _this.refreshFlag = true
        let imgsArray = [];
        uni.previewImage({
          urls: [this.imagesPath[0]]
        });
      },
      recognizeCar(item) {
        uni.setStorageSync('isSetSjxx', 'net');
        this.$tab.reLaunch(`/packageB/pages/common/vehicle-editing/vehicle-editing?id=${item.id}`);
      },
      //接单生成运单
      async handleJieDan() {
        this.waybillData.waybillRespVO.carBrand = this.selectedCar
        //校验参数
        if (!this.waybillData.waybillRespVO.carBrand) {
          toast('请选择车辆')
          return
        }
        if (!this.tareWeight) {
          toast('请输入0.01-200的矿发皮重')
          return
        }
        if (!this.grossWeight) {
          toast('请输入0.01-200的矿发毛重')
          return
        }
        if (!this.netWeight || (this.netWeight < 0.01 || this.netWeight > 200)) {
          toast('矿发净重范围为0.01-200,请核实')
          return
        }
        const calculatedNetWeight = (Number(this.grossWeight) - Number(this.tareWeight)).toFixed(2);
        const inputNetWeight = Number(this.netWeight).toFixed(2);
        if (Number(calculatedNetWeight) !== Number(inputNetWeight)) {
          showConfirm(`矿发数据有误,请重新输入`)
          return
        }
        if (!this.datetimesingle) {
          toast('请选择矿发时间')
          return
        }
        if (!this.waybillData.waybillRespVO.uuid) {
          toast('请上传矿发磅单');
          return;
        }
        this.waybillData.waybillRespVO.sealPhotographs = this.sealpictures.map(item => item.url);
        if (this.isSealpicturesFlag && this.waybillData.waybillRespVO.sealPhotographs.length === 0) {
          toast('请上传铅封照片');
          return;
        }
        this.waybillData.waybillRespVO.freightCollectionType = this.receiptIdValue
        this.waybillData.waybillRespVO.freightCollectionAccountId = this.accountIdValue
        this.waybillData.waybillRespVO.freightCollectionAccount = this.accountValue
        this.waybillData.waybillRespVO.netGoodsServiceCode = this.ServiceCode
        if (this.isNetFlag && this.isFlag) {
          if (!this.waybillData.waybillRespVO.freightCollectionType) {
            toast('请选择收款方式')
            return
          }
          if (!this.waybillData.waybillRespVO.freightCollectionAccountId && !this.backImgAddShow) {
            toast('请选择收款账户')
            return
          } else if (!this.waybillData.waybillRespVO.freightCollectionAccountId && this.backImgAddShow) {
            toast('请选择收款银行卡')
            return
          }
        }
        if (!this.waybillData.waybillRespVO?.uuid && !this.OreDevelopment[0] &&
          this.waybillData.waybillRespVO?.planType == 1) {
          toast('请上传磅单照片')
          return
        }
        const validWaybill = await this.findDriverWaybill()
        if (!validWaybill.purchaseStatus) {
          toast(validWaybill.purchaseMessage)
          return
        }
        if (!validWaybill.saleStatus) {
          toast(validWaybill.saleMessage)
          return
        }
        if (!this.isFlag) {
          uni.showModal({
            title: '继续接单',
            content: '未选择运费收款信息，后续需要手动补传，您确认继续接单吗？',
            success: (res) => {
              if (res.confirm) {
                //TODO 接单页面验证通过，再验证钱包余额（如果需要接单费用）
                if (this.payAmount > 0) {
                  //弹出接单支付确认框-->支付确认弹框接单
                  this.$refs['payConfirmDialog'].open("bottom");
                } else {
                  this.handleOrderNoPay()
                }
              } else if (res.cancel) {
                return
              }
            }
          });
        } else {
          //TODO 接单页面验证通过，再验证钱包余额（如果需要接单费用）
          if (this.payAmount > 0) {
            //弹出接单支付确认框-->支付确认弹框接单
            this.$refs['payConfirmDialog'].open("bottom");
          } else {
            this.handleOrderNoPay()
          }
        }
      },
      // 无费用直接接单
      async handleOrderNoPay() {
        if (this.isLoading) return
        this.isLoading = true
        let driverMoney = await getDriverMoney()
        if (driverMoney.code == 0) {
          if (Number(driverMoney.data.balance / 100) < this.payAmount) {
            //2.余额不够，跳转到充值界面
            toast("钱包余额不足，请充值")
          } else {
            //无费用直接接单
            this.waybillData.waybillRespVO.orderCost = this.payAmount * 100
            this.waybillData.waybillRespVO.uuid = this.OreDevelopment[0].url
            this.waybillData.waybillRespVO.supId = uni.getStorageSync('supIdFlag')
            this.waybillData.waybillRespVO.mineralNetWeight = Number(this.netWeight)
            this.waybillData.waybillRespVO.mineralTareWeight = Number(this.tareWeight)
            this.waybillData.waybillRespVO.mineralGrossWeight = Number(this.grossWeight)
            this.waybillData.waybillRespVO.freightCollectionAccount = this.accountValue
            this.waybillData.waybillRespVO.mineralTime = this.datetimesingle
            this.waybillData.waybillRespVO.userId = uni.getStorageSync('curUserId')
            this.waybillData.waybillRespVO.enterId = getTenantId()
            this.waybillData.waybillRespVO.openId = getOpenId()
            this.waybillData.waybillRespVO.planNo = this.planId
            try {
              let res = await addWaybillLists(this.waybillData.waybillRespVO);
              if (res.code == '200') {
                uni.removeStorageSync('supIdFlag')
                this.waybillDialogFlag = false
                // this.linkToPage()
                this.isOtherTip = this.lineupSwitch === 0 ? true : false
                this.$refs['jdcgPop'].open('bottom');
                this.startCountdown()
              } else if (res.code == '12000') {
                this.blacklistTip = res.msg
                this.showBlacklistTip = true
              } else {
                toast(`${res.msg}`)
              }
            } catch (e) {
              this.isLoading = false
              return false;
            }
            this.isLoading = false
          }
        }
      },
      // 支付确认弹框接单
      async handleOrderPay() {
        if (this.isLoading) return
        this.isLoading = true
        let driverMoney = await getDriverMoney()
        if (driverMoney.code == 0) {
          if (Number(driverMoney.data.balance / 100) < this.payAmount) {
            //2.余额不够，跳转到充值界面
            toast("钱包余额不足，请充值")
          } else {
            //1.余额足够：直接支付
            //直接接单，把需要的费用传给接口
            this.waybillData.waybillRespVO.orderCost = this.payAmount * 100
            this.waybillData.waybillRespVO.uuid = this.OreDevelopment[0].url
            this.waybillData.waybillRespVO.supId = uni.getStorageSync('supIdFlag')
            this.waybillData.waybillRespVO.mineralNetWeight = Number(this.netWeight)
            this.waybillData.waybillRespVO.mineralTareWeight = Number(this.tareWeight)
            this.waybillData.waybillRespVO.mineralGrossWeight = Number(this.grossWeight)
            this.waybillData.waybillRespVO.freightCollectionAccount = this.accountValue
            this.waybillData.waybillRespVO.mineralTime = this.datetimesingle
            this.waybillData.waybillRespVO.userId = uni.getStorageSync('curUserId')
            this.waybillData.waybillRespVO.enterId = getTenantId()
            this.waybillData.waybillRespVO.openId = getOpenId()
            this.waybillData.waybillRespVO.planNo = this.planId
            let res = await addWaybillLists(this.waybillData.waybillRespVO);
            if (res.code == '200') {
              uni.removeStorageSync('supIdFlag')
              this.waybillDialogFlag = false
              // this.linkToPage()
              this.exit()
              this.isOtherTip = this.lineupSwitch === 0 ? true : false
              this.$refs['jdcgPop'].open('bottom');
              this.startCountdown()
            } else if (res.code === '12000') {
              this.blacklistTip = res.msg
              this.showBlacklistTip = true
            } else {
              toast(`${res.msg}`)
              this.payAmount = 0
              this.getLatestWayBill()
            }
          }
          this.isLoading = false
        }

        // let driverMoney = await getDriverMoney()
        // if (driverMoney.code == 0) {
        //   if (Number(driverMoney.data.balance / 100) < this.payAmount) {
        //     //2.余额不够，跳转到充值界面
        //     toast("钱包余额不足，请充值")
        //   } else {
        //     //1.余额足够：直接支付 
        //     const data = await getWaybNbyTenantid(getDriverId(), uni.getStorageSync('ysjhData').tenantId, this.waybillData.waybillRespVO.planType)
        //     if (data.code == 200) {
        //       this.waybillData.waybillRespVO.waybillNo = data.data.waybillNo
        //       setWayBillNo(this.waybillData.waybillRespVO.waybillNo)
        //       let resBalance = await payWaybillCost({
        //         "waybillNo": this.waybillData.waybillRespVO.waybillNo,
        //         "orderCost": Number(this.payAmount) * 100,
        //         queueType: 1
        //       });
        //       if (resBalance.code == 0) {
        //         //支付成功后创建一个接单
        //         this.waybillData.waybillRespVO.uuid = this.OreDevelopment[0].url
        //         this.waybillData.waybillRespVO.supId = uni.getStorageSync('supIdFlag')
        //         this.waybillData.waybillRespVO.mineralNetWeight = Number(this.netWeight)
        //         this.waybillData.waybillRespVO.mineralTareWeight = Number(this.tareWeight)
        //         this.waybillData.waybillRespVO.mineralGrossWeight = Number(this.grossWeight)
        //         this.waybillData.waybillRespVO.freightCollectionAccount = this.accountValue
        //         this.waybillData.waybillRespVO.mineralTime = this.datetimesingle
        //         this.waybillData.waybillRespVO.userId = uni.getStorageSync('curUserId')
        //         this.waybillData.waybillRespVO.enterId = getTenantId()
        //         this.waybillData.waybillRespVO.openId = getOpenId()
        //         this.waybillData.waybillRespVO.planNo = this.planId
        //         let res = await addWaybillLists(this.waybillData.waybillRespVO);
        //         if (res.code == '200') {
        //           uni.removeStorageSync('supIdFlag')
        //           this.waybillDialogFlag = false
        //           this.linkToPage()
        //           this.exit()
        //         } else if (res.code === '12000') {
        //           this.blacklistTip = res.msg
        //           this.showBlacklistTip = true
        //         } else {
        //           toast(`${res.msg}`)
        //           this.payAmount = 0
        //           this.getLatestWayBill()
        //         }
        //       } else {
        //         toast(resBalance.msg)
        //       }
        //     }
        // }
      },
      confirmJieDan() {
        if (this.isCounting) return;
        this.$refs['jdcgPop'].close();
        this.linkToPage();
      },
      linkToPage() {
        if (this.lineupSwitch === 0) {
          uni.setStorageSync('orderType', 1);
          this.$tab.reLaunch(`/pages/index?carno=${this.selectedCar}`);
          return;
        }
        if (this.waybillData.waybillRespVO.planType == 1) {
          setTimeout(() => {
            uni.setStorageSync('orderType', 1);
            this.$tab.reLaunch('/pages/waybill?type=deliver');
          }, 1000);
        } else {
          this.$tab.reLaunch('/pages/waybill?type=deliver');
        }
      },
      async findLineupSwitchByTenant() {
        const res = await findLineupSwitchByTenant(getTenantId());
        if (res.code === '200') {
          // 排队开关
          this.lineupSwitch = res.data?.lineupSwitch;
        }
      },
      handleAddCar() {
        this.setStorageDatas()
        uni.setStorageSync('isSetSjxx', 'net');
        uni.navigateTo({
          url: "/packageB/pages/common/vehicle-editing/vehicle-authentica?type=code"
        });
      },
      handleProd(item) {
        this.selectedProd = item.proName
        this.waybillData.waybillRespVO.proId = item.proId
        this.$refs['prodPopup'].close();
      },
      async handleCar(item) {
        //先去校验该车辆是否有正在执行中的运单
        let res = await checkRuningCar({
          "vehicleNo": item.vehicleNo,
          "enterId": getTenantId()
        })
        if (res.code != '200') {
          toast(`${res.msg}`)
          return
        }
        this.carBrandId = item.id
        this.selectedCar = item.vehicleNo;
        this.waybillData.waybillRespVO.carBrand = item.vehicleNo;
        this.checkCarAndImagNull()
        uni.setStorageSync('vehicleNoByCode', item.vehicleNo);

        if (this.isNetFlag) {
          this.failedCar = item.remark
          this.waybillData.waybillRespVO.uploadStatusCar = item.auditStatus == undefined ? 0 : item.auditStatus
          //接单为网货时，选择车辆后获取收款信息
          this.getReceiptTypeList(item.vehicleNo)
        }
        this.$refs['popup'].close();
      },
      checkCarAndImagNull() {
        this.loading = this.waybillData.waybillRespVO?.planType == 1 ?
          (!!this.waybillData.waybillRespVO.carBrand ? true : false) :
          ((!!this.waybillData.waybillRespVO.carBrand && !!this.waybillData.waybillRespVO.uuid) ? true : false)
      },
      change(e) {
      },
      open() {
        this.$refs['popup'].open('bottom');
      },
      openCard() {
        this.$refs['popupCard'].open('bottom');
      },
      openReceipt() {
        this.$refs['popupReceipt'].open('bottom');
      },
      openAccount() {
        this.$refs['popupAccount'].open('bottom');
      },
      openProdct() {
        this.$refs['prodPopup'].open('bottom');
      },
      // 获取司机最新运单详情
      async getLatestWayBill(type) {
        try {
          let res = await getWayBillDetailLatest({
            "tenant-id": getTenantId(),
            "Authorization": 'Bearer ' + getAccessToken(),
          }, { businessType: 1 });
          if (res.code == 0) {
            const status = res.data?.waybillStatus
            if (status === 2 && this.lineupSwitch == 0) {
              uni.setStorageSync('orderType', 1);
              const id = res.data.waybillNo
              if (id) {
                this.$tab.reLaunch(`/pages/index?codes=true&id=${id}`)
              }
              return
            }
            if (status === 2 && this.lineupSwitch == 1) {
              uni.setStorageSync('orderType', 1);
              this.$tab.switchTab(`/pages/waybill?type=deliver`);
              return
            }
            if ([0, 1, 3, 4, 5, 6, 10].includes(status)) {
              uni.setStorageSync('orderType', 1);
              this.$tab.switchTab(`/pages/waybill?type=deliver`);
              return
            }
            this.isJiedanRead = true
            this.getTransPlanData(uni.getStorageSync('ysjhData').planId)
          } else {
            toast(res.msg);
          }
        } catch (e) {
          return false;
        }
      },
      //获取车辆列表
      async getCarList(networkFreight) {
        try {
          //遍历对象过滤空值
          let data = {
            pageNo: 1,
            pageSize: 100,
          };
          let isNetFlagData = {
            pageNo: 1,
            pageSize: 100,
            networkFreight: networkFreight
          };
          if (this.isNetFlag) {
            let res = await getVehicle(isNetFlagData);
            if (res.code == 0) {
              this.vehicleList = res.data.list;
            }
          } else {
            let res = await getVehicle(data);
            if (res.code == 0) {
              this.vehicleList = res.data.list;
            }
          }
        } catch (e) {
          return false;
        }
      },

      select(e, type) {
        let that = this;
        that.isJieDan = true;
        let selectedImages = e.tempFiles;
        wx.showLoading({ title: '正在上传...', mask: true });
        // 异步并行上传每一张图片
        const uploadPromises = selectedImages.map((image, index) => {
          let curSize = image.size;
          let qualityVal = 100;
          let initnum = 0.31024 * 1024;

          if (curSize > initnum) {
            qualityVal = 100 / (curSize / initnum);
          }
          qualityVal = Math.max(80, qualityVal);

          return new Promise((resolve, reject) => {
            uni.compressImage({
              src: image.path,
              quality: qualityVal,
              success: (resp) => {
                if (type === 'oreDevelopment') {
                  that.uploadFiles(resp.tempFilePath, index, 'OreDevelopment').then(resolve).catch(reject);
                } else if (type === 'sealPictures') {
                  that.uploadFiles(resp.tempFilePath, index, 'sealPictures').then(resolve).catch(reject);
                }
              },
              fail: (error) => {
                console.error('图片压缩失败', error);
                reject(error);
              },
            });
          });
        });

        // 使用 Promise.all 并行处理图片上传
        Promise.all(uploadPromises)
          .then(() => {
            wx.hideLoading();
          })
          .catch(() => {
            wx.hideLoading();
            uni.showToast({ title: '上传失败' });
          });
      },

      uploadFiles(filepath, index, type) {
        let _ = this;
        return new Promise((resolve, reject) => {
          uni.uploadFile({
            url: config.baseUrl + '/infra/file/upload',
            filePath: filepath,
            name: 'file',
            header: {
              "Content-Type": "multipart/form-data",
              'Authorization': 'Bearer ' + getAccessToken(),
            },
            success: (res) => {
              if (res.statusCode === 200) {
                const responseData = JSON.parse(res.data);
                const pictureFormat = {
                  url: responseData.data,
                  extname: 'jpg',
                  name: index + '.jpg'
                };
                if (type === 'OreDevelopment') {
                  _.OreDevelopment.push(pictureFormat); // 添加矿发磅单图片
                  _.waybillData.waybillRespVO.uuid = responseData.data;
                } else if (type === 'sealPictures') {
                  _.sealpictures.push(pictureFormat); // 添加铅封图片
                }
                resolve();
              } else {
                if (res.statusCode === 413) {
                  toast('上传图片过大，请重新上传，不要选择原图');
                } else {
                  toast('上传失败，状态码:' + res.statusCode);
                }
                reject(new Error('上传失败'));
              }
            },
            fail: (err) => {
              uni.showToast({ title: '上传失败' });
              reject(err);
            }
          });
        });
      },
      //删除图片
      deletephoto(index, type) {
        let _ = this;
        if (type === 'oreDevelopment') {
          _.OreDevelopment.splice(index, 1);
          this.waybillData.waybillRespVO.uuid = undefined
          if (_.OreDevelopment.length === 0) {
            _.currentWIndow = 0;
            _.waybillDialogFlag = false;
          }
        } else if (type === 'sealpictures') {
          _.sealpictures.splice(index, 1);
          if (_.sealpictures.length === 0) {
            _.currentWIndow = 0;
            _.waybillDialogFlag = false;
          }
        }
      },
      resetWaybillData() {
        this.waybillData = {
          waybillRespVO: {
            uploadStatus: undefined,
            uploadStatusCar: undefined,
            transportPlanId: undefined,
            purchaseId: undefined,
            purchaser: undefined,
            proName: undefined,
            proId: undefined,
            landingPlaceId: undefined,
            landingPlace: undefined,
            cargoOwnerld: undefined,
            cargoOwnerName: undefined,
            netCargoCompanyId: undefined,
            netCargoCompanyName: undefined,
            landingPoint: undefined,
            landingPointName: undefined,
            agentId: undefined,
            agentName: undefined,
            informationFee: undefined,
            settlementBasis: undefined,
            erasureRule: undefined,
            loadingSiteId: undefined,
            loadingSiteName: undefined,
            supName: undefined,
            freight: undefined,
            planType: undefined,
            cusTransport: undefined,
            carName: undefined,
            carCard: undefined,
            driverId: undefined,
            carPhone: undefined,
            uuid: undefined,
            supId: undefined,
            mineralGrossWeight: undefined,
            mineralTareWeight: undefined,
            mineralNetWeight: undefined,
            mineralTime: undefined,
            userId: undefined,
            enterId: undefined,
            openId: undefined,
            planNo: undefined,
            planTypeName: undefined,
            sealPhotographs: [],
          },
          hours: 0,
          minutes: 0,
          currentLineupCount: 0,
          enableStatus: undefined,
          sealpictures: [],
          OreDevelopment: [],
        }
        if (this.OreDevelopment.length) {
          this.waybillData.waybillRespVO.uuid = this.OreDevelopment[0]?.url
        }
      },
      async getTransPlanData(id) {
        let _ = this
        _.curType = 2
        _.resetWaybillData()
        try {
          let res = await getTransPlanDetail({
            planNo: id,
            isOperation: uni.getStorageSync('ysjhData').isOperation
          });
          _.currentStatus = true
          if (res.code == "200") {
            if (res.data.planType == 1) {//采购
              //获取铅封图片开关配置
              if (res.data.sealPhotograph === 1) {
                this.isSealpicturesFlag = true
              }
              let resCost = await getWaybCost({
                planType: res.data.planType,
                customerOrPurchaserId: res.data.purchaserId
              })
              if (resCost.code == 0) {
                this.payOriginalVal = resCost.data
                if (resCost.data !== 0 && resCost.data !== null) {
                  this.payAmount = parseFloat(resCost.data / 100).toFixed(2)
                }
              }
              //TODO 获取运单编号
              // let data = await getWaybNbyTenantid(getDriverId(), uni.getStorageSync('ysjhData').tenantId, res.data.planType)
              // if (data.code == 200) {
              //   this.waybillData.waybillRespVO.waybillNo = data.data.waybillNo
              //   setWayBillNo(this.waybillData.waybillRespVO.waybillNo)
              //   this.payCostFlag = data.data.tradeStatus
              //   if (data.data.tradeStatus) {
              //     //TODO 获取费用配置
              //     let resCost = await getWaybCost({
              //       planType: res.data.planType,
              //       customerOrPurchaserId: res.data.purchaserId
              //     })
              //     if (resCost.code == 0) {
              //       this.payAmount = parseFloat(resCost.data / 100).toFixed(2)
              //     }
              //   }
              // }
            }

            let dateRes = getCurrenDate()
            _.curDateTime = dateRes.curYear + '-' + dateRes.curMonth + '-' + dateRes.curDay + ' ' + dateRes.curHour + ':' + dateRes.curMinute + ':' + dateRes.curSecond
            uni.removeStorageSync('currentLinePageData');
            uni.setStorageSync('currentLinePageData', res.data);
            uni.setStorageSync('curUserId', res.data.userId);
            let driverInfo = uni.getStorageSync('sjxxData');
            _.carListFlag = false
            _.waybillDialogFlag = true
            _.waybillData.waybillRespVO.purchaseId = res.data.purchaseId
            _.waybillData.waybillRespVO.purchaser = res.data.purchaser
            _.waybillData.waybillRespVO.supId = res.data.supId
            _.waybillData.waybillRespVO.supName = res.data.supName
            _.waybillData.waybillRespVO.proId = res.data.proId
            _.waybillData.waybillRespVO.proName = res.data.proName
            _.waybillData.waybillRespVO.loadingSiteId = res.data.loadingSiteId
            _.waybillData.waybillRespVO.loadingSiteName = res.data.loadingSiteName
            _.waybillData.waybillRespVO.landingPlaceId = res.data.landingPlaceId
            _.waybillData.waybillRespVO.landingPlace = res.data.landingPlace
            _.waybillData.waybillRespVO.freight = res.data.freight
            _.waybillData.waybillRespVO.cargoOwnerld = res.data.cargoOwnerld
            _.waybillData.waybillRespVO.transportPlanId = res.data.id
            _.waybillData.waybillRespVO.cargoOwnerName = res.data.cargoOwnerName
            _.waybillData.waybillRespVO.netCargoCompanyId = res.data.netCargoCompanyId
            _.waybillData.waybillRespVO.netCargoCompanyName = res.data.netCargoCompanyName
            _.waybillData.waybillRespVO.agentId = res.data.agentId
            _.waybillData.waybillRespVO.agentName = res.data.agentName

            _.waybillData.waybillRespVO.informationFee = res.data.informationFee
            _.waybillData.waybillRespVO.settlementBasis = res.data.settlementBasis//结算依据
            _.waybillData.waybillRespVO.erasureRule = res.data.erasureRule//抹零规则
            _.waybillData.waybillRespVO.landingPoint = res.data.landingPoint//卸货点id
            _.waybillData.waybillRespVO.landingPointName = res.data.landingPointName//卸货点名称
            _.waybillData.waybillRespVO.planType = res.data.planType

            _.waybillData.waybillRespVO.cusTransport = res.data.cusTransport
            _.payeeInfoParam.networkFreight = res.data.netCargoCompanyId
            _.payeeInfoParam.goodsId = res.data.goodsId
            _.getCarList(res.data.netCargoCompanyId);//获取车辆信息
            if (this.isNetFlag) {
              //接单为网货时，获取司机信息及上传状态
              this.getDriverDataList(res.data.netCargoCompanyId)
            } else {
              //接单为非网货时，获取司机信息走之前逻辑
              _.waybillData.waybillRespVO.carName = driverInfo.driverName
              _.waybillData.waybillRespVO.carCard = driverInfo.idNo
              _.driverCard = driverInfo.idNo.slice(0, 3) + '****' + driverInfo.idNo.slice(-3)
              _.waybillData.waybillRespVO.driverId = driverInfo.id
              _.waybillData.waybillRespVO.carPhone = driverInfo.mobile
            }
            uni.setStorageSync('supIdFlag', res.data.supId)
            if (_.isJiedanRead && res.data.purchaserId == 6) {
              _.showReadMe = true
            }
          } else {
            // _.tipsMess = res.msg
            // _.$refs['tipsShow'].open();
            toast(res.msg)
          }
        } catch (e) {
          return false;
        }
      },
      closeTipsWin() {
        this.$refs['tipsShow'].close();
      },
      showPageFromStorage() {

        let _ = this
        _.currentStatus = true
        let data = uni.getStorageSync('currentLinePageData');
        _.carListFlag = false
        _.payAmount = uni.getStorageSync('purchasePayNum');
        //获取铅封图片开关配置
        if (data.sealPhotograph === 1) {
          this.isSealpicturesFlag = true
        }
        let datas = uni.getStorageSync('ysjhData')
        if (!!datas?.onlineGoodsSwitch) {//获取到缓存数据
          this.isNetFlag = datas?.onlineGoodsSwitch == "1" ? true : false
        }
        let driverInfo = uni.getStorageSync('sjxxData');
        _.waybillData.waybillRespVO.purchaseId = data.purchaseId
        _.waybillData.waybillRespVO.waybillNo = getWayBillNo()
        _.waybillData.waybillRespVO.purchaser = data.purchaser
        _.waybillData.waybillRespVO.supId = data.supId
        _.waybillData.waybillRespVO.supName = data.supName
        _.waybillData.waybillRespVO.proId = data.proId
        _.waybillData.waybillRespVO.proName = data.proName

        _.waybillData.waybillRespVO.loadingSiteId = data.loadingSiteId
        _.waybillData.waybillRespVO.loadingSiteName = data.loadingSiteName
        _.waybillData.waybillRespVO.landingPlaceId = data.landingPlaceId
        _.waybillData.waybillRespVO.landingPlace = data.landingPlace
        _.waybillData.waybillRespVO.freight = data.freight
        _.waybillData.waybillRespVO.cargoOwnerld = data.cargoOwnerld
        _.waybillData.waybillRespVO.transportPlanId = data.id
        _.waybillData.waybillRespVO.cargoOwnerName = data.cargoOwnerName
        _.waybillData.waybillRespVO.netCargoCompanyId = data.netCargoCompanyId
        _.waybillData.waybillRespVO.netCargoCompanyName = data.netCargoCompanyName
        _.waybillData.waybillRespVO.agentId = data.agentId
        _.waybillData.waybillRespVO.agentName = data.agentName

        _.waybillData.waybillRespVO.informationFee = data.informationFee
        _.waybillData.waybillRespVO.settlementBasis = data.settlementBasis//结算依据
        _.waybillData.waybillRespVO.erasureRule = data.erasureRule//抹零规则
        _.waybillData.waybillRespVO.landingPoint = data.landingPoint//卸货点id
        _.waybillData.waybillRespVO.landingPointName = data.landingPointName//卸货点名称
        _.waybillData.waybillRespVO.planType = data.planType
        _.waybillData.waybillRespVO.cusTransport = data.cusTransport
        _.payeeInfoParam.networkFreight = data.netCargoCompanyId
        _.payeeInfoParam.goodsId = data.goodsId
        _.getCarList(data.netCargoCompanyId);//获取车辆信息
        if (this.isNetFlag) {
          //接单为网货时，获取司机信息及上传状态
          this.getDriverDataList(data.netCargoCompanyId)
        } else {
          //接单为非网货时，获取司机信息走之前逻辑
          _.waybillData.waybillRespVO.carName = driverInfo.driverName
          _.waybillData.waybillRespVO.carCard = driverInfo.idNo
          _.driverCard = driverInfo.idNo.slice(0, 3) + '****' + driverInfo.idNo.slice(-3)
          _.waybillData.waybillRespVO.driverId = driverInfo.id
          _.waybillData.waybillRespVO.carPhone = driverInfo.mobile
          _.selectedCar = uni.getStorageSync('vehicleNoByCode');
          _.waybillData.waybillRespVO.carBrand = uni.getStorageSync('vehicleNoByCode');
        }

        _.OreDevelopment = uni.getStorageSync('loadingWeighbridgeByCode') || [];
        _.waybillData.waybillRespVO.uuid = _.OreDevelopment.length <= 0 ? undefined : _.OreDevelopment[0].url
        if (this.isSealpicturesFlag) {
          _.sealpictures = uni.getStorageSync('sealpicturesByCode', _.sealpictures);
          _.waybillData.waybillRespVO.sealPhotographs = _.sealpictures.length <= 0 ? undefined : _.sealpictures[0].url;
        }
        _.netWeight = uni.getStorageSync('netweightByCode');
        _.tareWeight = uni.getStorageSync('tareWeightByCode');
        _.grossWeight = uni.getStorageSync('grossWeightByCode');
        _.datetimesingle = uni.getStorageSync('datetimeJiedanByCode');
        _.waybillData.waybillRespVO.mineralTime = uni.getStorageSync('datetimeJiedanByCode');
        _.waybillData.waybillRespVO.mineralNetWeight = uni.getStorageSync('netweightByCode');
        _.waybillData.waybillRespVO.mineralTareWeight = uni.getStorageSync('tareWeightByCode');
        _.waybillData.waybillRespVO.mineralGrossWeight = uni.getStorageSync('grossWeightByCode');
        _.checkCarAndImagNull()
        _.currentWIndow = 1
        _.waybillDialogFlag = true
        console.log("XXXXXX车牌号---=", _.selectedCar)
        console.log("XXXXXXOreDevelopment---=", _.OreDevelopment)
        console.log("XXXXXXsealpictures---=", _.sealpictures)
        _.removeStorageDatas()
      },

      // 获取登录状态
      async getLoginStatus() {
        console.log('判断登录状态是获取atoken', getAccessToken());
        // let code = await func.wxLogin();
        // console.log(code,'code================')
        if (getAccessToken()) {
          //已经登录
          this.rowNumberData = []
          this.getRowList();
        } else {
          //没登陆 获取租户列表看是否以前注册过
          this.loginNew()
        }
      },
      //用户无感知登录
      async loginNew() {
        //获取wx code
        let code1 = await func.wxLogin();
        console.log(code1, '这是第一次获取的code================')
        let openid = await getOpenIdByCode(code1);
        console.log(openid.data, '这是第一次获取的openid================')
        this.getTenantids(openid.data)
      },
      async login(num) {
        //获取wx code
        let code = await func.wxLogin();
        let data = {
          phoneCode: num,
          loginCode: code
        };

        wxPhoneLogin(data).then((res) => {
          if (res.code == 0) {
            setToken({
              'accessToken': res.data.accessToken,
              'refreshToken': res.data.refreshToken,
            })
            setDriverId(res.data.userId)
            this.switchText = "我的排号"
            this.getLoginStatus();
          }
        });
      },
      //获取司机租户信息
      async getTenantids(openid) {
        //获取wx code
        this.openid = openid
        let res1 = await getTenantsByOpenId(openid);
        if (res1.code == 0) {
          if (res1.data.length == 0) {
            this.$tab.reLaunch('/pages/login?type=code');
            return
          }
          this.tenantList = res1.data;
          if (res1.data.length == 1) {
            //直接用
            setTenantId(res1.data[0].id)
            let number = await getPhoneByOpenid(openid);
            console.log(number, '这是租户为一个的时候获取回来的手机号================')
            this.login(number.data);
          } else {
            console.log('这是获取到了多个租户列表==========:', res1.data);
            //跳转到租户下拉选择页面
            // this.$refs['tenantsDialog'].open('bottom');
            this.$tab.reLaunch(`/packageA/pages/tenant?openid=${openid}`);
          }
        }
      },

      //获取排号信息列表
      async getRowList() {
        try {
          //遍历对象过滤空值
          let data = {};
          Object.keys(this.queryParam).forEach((item) => {
            if (this.queryParam[item]) {
              data[item] = this.queryParam[item];
            }
          });
          this.pageParams.isMore = 'loading';
          let res = await getLineUpByDriver(data);
          if (res.code == 0) {
            if (this.queryParam.pageNo == 1) {
              this.rowNumberData = res.data.list;
            } else {
              this.rowNumberData = [...this.rowNumberData, ...res.data.list];
            }

            if (res.data.total == this.rowNumberData.length) {
              this.pageParams.isMore = 'noMore';
            } else {
              this.pageParams.isMore = 'more';
            }
          }
          //停止下拉刷新
          wx.hideNavigationBarLoading();
          //停止下拉刷新
          wx.stopPullDownRefresh();
        } catch (e) {
          return false;
        }
      },
      async findDriverWaybill() {
        const data = {
          vehicleNo: this.selectedCar,
          driverIdCard: this.waybillData.waybillRespVO.carCard,
          enterId: getTenantId()
        }
        const res = await findDriverWaybill(data);
        if (res.code === '200') {
          return res?.data;
        }
        return {
          purchaseStatus: false,
          message: res?.msg
        };

      },
      //阅读
      showTip(event) {
        this.showBlacklistTip = event
      },
      startCountdown() {
        const hasCountdown = uni.getStorageSync('hasCountdown');
        if (!hasCountdown) {
          this.isCounting = true;
          const timer = setInterval(() => {
            if (this.countdown > 0) {
              this.countdown--;
            } else {
              this.isCounting = false;
              clearInterval(timer);
              // 倒计时结束后，设置标记
              uni.setStorageSync('hasCountdown', true);
            }
          }, 1000);
        }
      }
    },
    async onLoad(options) {
      await this.findLineupSwitchByTenant()
      this.planId = uni.getStorageSync('ysjhData').planId
      if (!!options) {
        if (!!options.codes) {
          //是从充值成功过来的 
          if (options?.codes == 'czback') {
            //获取到缓存数据
            this.showPageFromStorage();
            return;
          }
          //是从接单过来的 
          let datas = uni.getStorageSync('ysjhData')
          if (!!datas?.planId) {//获取到缓存数据
            this.getLatestWayBill()
          }
          if (!!datas?.onlineGoodsSwitch) {//获取到缓存数据
            this.isNetFlag = datas?.onlineGoodsSwitch == "1" ? true : false
          }
        } else {
          if (JSON.stringify(options) == "{}") {
            this.curType = 1
            this.getLoginStatus()
            return
          }
          uni.setNavigationBarTitle({
            title: '接单'
          });
        }
      }
    },
    onShow() {
      uni.setNavigationBarTitle({
        title: '接单'
      });
      // if (uni.getStorageSync('isSetSjxx')) {
      //   this.showPageFromStorage()
      // }
    },
    computed: {
      imagesSuccess() {
        if (this.$store.state.user.curTypeColor == '#D22C2C') {
          return config.baseImgUrl + '/sucess1.png';
        } else if (this.$store.state.user.curTypeColor == '#409EFE') {
          return config.baseImgUrl + '/sucess.png';
        } else {
        }
      },
      checkImg() {
        if (this.$store.state.user.curTypeColor == '#D22C2C') {
          return config.baseImgUrl + '/checked1.png';
        } else if (this.$store.state.user.curTypeColor == '#409EFE') {
          return config.baseImgUrl + '/checked.png';
        } else {
          return config.baseImgUrl + '/checked.png';
        }
      },
      uncheckImg() {
        return config.baseImgUrl + '/unchecked.png';
      },
      backImg() {
        if (this.$store.state.user.curTypeColor == "#D22C2C") {
          return config.baseImgUrl + '/cards1.png'
        } else if (this.$store.state.user.curTypeColor == "#409EFE") {
          return config.baseImgUrl + '/cards.png'
        } else { return config.baseImgUrl + '/cards.png' }
      },
      carImg() {
        if (this.$store.state.user.curTypeColor == "#D22C2C") {
          return config.baseImgUrl + '/car1.png'
        } else if (this.$store.state.user.curTypeColor == "#409EFE") {
          return config.baseImgUrl + '/car.png'
        } else {
          return config.baseImgUrl + '/car.png'
        }
      },
      balanceImg() {
        if (this.$store.state.user.curTypeColor == "#D22C2C") {
          return config.baseImgUrl + '/balance1.png'
        } else if (this.$store.state.user.curTypeColor == "#409EFE") {
          return config.baseImgUrl + '/balance.png'
        } else {
          return config.baseImgUrl + '/balance.png'
        }
      },
      backImgAdd() {
        if (this.$store.state.user.curTypeColor == "#D22C2C") {
          return config.baseImgUrl + '/add1.png'
        } else if (this.$store.state.user.curTypeColor == "#409EFE") {
          return config.baseImgUrl + '/add.png'
        } else { return config.baseImgUrl + '/add.png' }
      }
    },
    onHide() {
    }
  };
</script>
<style lang="scss" scoped>
  .imageStyle {
    width: 204rpx;
    position: relative;
    height: 196rpx;

    .close-icon {
      position: absolute;
      top: 8rpx;
      right: 8rpx;
      z-index: 9;
    }
  }

  .status {
    font-size: 26.66rpx;
    padding: 0 20rpx;
    text-align: center;
    border-radius: 10rpx;
    display: block;
    height: 35px;
    line-height: 29px;
  }

  .back-meng {
    background: rgba(0, 0, 0, 0.6);
    position: absolute;
    top: 0;
    z-index: 8;
    left: 0;
    width: 100vw;
    height: 100vh;
    overflow: hidden;
  }

  .phxx-itemss {
    box-sizing: border-box;
    background: #fff;
    border-radius: 30rpx;
    width: 90vw;
    position: absolute;
    top: 12%;
    z-index: 9;
    left: 5vw;

    .header {
      width: 100%;
      height: 96rpx;
      line-height: 96rpx;
      border-bottom: 2rpx solid #EAEAEA;
      text-align: center;
      color: #000;
      font-size: 16px;
      font-weight: 600;
    }

    .top {
      padding: 30rpx;
      font-size: 15px;

      .tit {
        margin-bottom: 20rpx;
      }
    }

    .btn {
      padding: 11rpx;

      button.not-read {
        background: #ccc !important;
        ;
      }
    }

  }

  .loading {
    position: relative;
  }

  .loading-icon {
    display: inline-block;
    width: 20px;
    height: 20px;
    border: 4px solid rgba(0, 0, 0, .1);
    border-left-color: transparent;
    border-radius: 50%;
    animation: spin 1s linear infinite;
    position: absolute;
    top: 29%;
    left: 36%;
    transform: translate(-50%, -50%);
  }

  ::v-deep.jdcgPop {
    background-color: #fff;
    width: 750rpx;
    height: 450rpx;

    .top {
      background-color: #fff;
      width: 750rpx;
      font-size: 14px;
      padding: 20rpx;

      .title-box {
        border-bottom: 1px dashed #ccc;
        padding-bottom: 20rpx;
        text-align: center;
        font-size: 18px;
        color: #000;
        font-weight: bold;

        .tit {
          padding: 15rpx 0;
        }

        .tit1 {
          image {
            width: 218rpx;
            height: 188rpx;
          }
        }
      }

      .body {
        font-size: 30rpx;
        color: #666;
        padding: 20rpx 24rpx 0 24rpx;

        .tit {
          padding-bottom: 20rpx;
          display: flex;
          align-items: center;

          .icon {
            width: 16rpx;
            height: 16rpx;
            min-width: 16rpx;
            background: rgba(64, 158, 254, 0.5);
            display: inline-block;
            border-radius: 50%;
            position: relative;
            margin-right: 10rpx;

            .icon-inner {
              position: relative;
              background-color: #409efe;
              width: 8rpx;
              height: 8rpx;
              border-radius: 50%;
              top: 2px;
              left: 5rpx;
            }
          }
        }
      }
    }
  }

  @keyframes spin {
    0% {
      transform: rotate(0deg);
    }

    100% {
      transform: rotate(360deg);
    }
  }
</style>